package com.haoran.dwz.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.haoran.dwz.common.security.UsmContextHolder;
import com.haoran.dwz.domain.entities.ShortURL;
import com.haoran.dwz.domain.entities.URLRecycleBin;
import com.haoran.dwz.rest.R;
import com.haoran.dwz.service.URLRecycleBinService;
import com.haoran.dwz.wrapper.PaginationWrapper;

import io.swagger.annotations.ApiOperation;

@Controller
@RequestMapping("recycle")
public class URLRecycleBinController {

	@Autowired
	private URLRecycleBinService urlRecycleBinService;

	@ApiOperation(value = "跳转页", hidden = true)
	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public String index(Model model) {
		return "url/recycle";
	}
	
	
	@ApiOperation("分页查询所有的短链接历史记录")
	@RequestMapping(value = "page-list", method = { RequestMethod.GET })
	@ResponseBody
	public PaginationWrapper findByPageable(ShortURL shortURL) {
		Sort sort = new Sort(Direction.DESC,"deleteTime", "lastUsedTime", "createTime");
		Pageable pageable = new PageRequest(shortURL.getPage()-1, shortURL.getLimit(), sort);
		Page<URLRecycleBin> entryByPageable = urlRecycleBinService.findByPageable(pageable);
		PaginationWrapper pageUtil = new PaginationWrapper(entryByPageable.getContent(), entryByPageable.getTotalElements(), shortURL.getLimit(),shortURL.getPage());
		return pageUtil;
	}
	
	@ApiOperation("删除回收站里的短链接记录")
	@RequestMapping(value = "remove", method = RequestMethod.POST)
	@ResponseBody
	public R delete(@RequestParam("ids[]") Long[] ids) {
		if (ids == null || ids.length == 0) {
			return R.success();
		} else {
			for (long id : ids) {
				if (urlRecycleBinService.exists(id)) {
					urlRecycleBinService.delete(id,UsmContextHolder.getUser().getUsername());
				}
			}
			return R.success();
		}
	}
}
